<template>
  <div class="container" v-if="$loadingRouteData">
    <p>loading...</p>
  </div>
  <div class="container" v-if="!$loadingRouteData">
    <div class="row">
      <breadcrumb :breadcrumbs="navItems"></breadcrumb>
    </div>
    <div class="row">
      <reactive-container :reactive="[3, 3, 6, 6]">
        <box box-title="新增" :box-content="reportData.news[0]">
          <small class="w-yesterday-profile clearfix">
            <label-text label-text="昨日"></label-text>
            <span class="w-secondary-value">{{ reportData.news[1] }}</span>
            <growth-label class="w-secondary-value w-rais-percent" 
              :new-value="reportRawData.news[0]" 
              :old-value="reportRawData.news[1]">
            </growth-label>
          </small>
        </box>
      </reactive-container>
      <reactive-container :reactive="[3, 3, 6, 6]">
        <box box-title="访次" :box-content="reportData.visited[0]">
          <small class="w-yesterday-profile clearfix">
            <label-text label-text="昨日"></label-text>
            <span class="w-secondary-value">{{ reportData.visited[1] }}</span>
            <growth-label class="w-secondary-value w-rais-percent" 
              :new-value="reportRawData.visited[0]" 
              :old-value="reportRawData.visited[1]">
            </growth-label>
          </small>
        </box>
      </reactive-container>
      <reactive-container :reactive="[3, 3, 6, 6]">
        <box box-title="订购" :box-content="reportData.orders[0]">
          <small class="w-yesterday-profile clearfix">
            <label-text label-text="昨日"></label-text>
            <span class="w-secondary-value">{{ reportData.orders[1] }}</span>
            <growth-label class="w-secondary-value w-rais-percent" 
              :new-value="reportRawData.orders[0]" 
              :old-value="reportRawData.orders[1]">
            </growth-label>
          </small>
        </box>
      </reactive-container>
      <reactive-container :reactive="[3, 3, 6, 6]">
        <box box-title="总用户" :box-content="reportData.users[0]">
          <small class="w-yesterday-profile clearfix">
            <label-text label-text="昨日"></label-text>
            <span class="w-secondary-value">{{ reportData.users[1] }}</span>
            <growth-label class="w-secondary-value w-rais-percent" 
              :new-value="reportRawData.users[0]" 
              :old-value="reportRawData.users[1]">
            </growth-label>
          </small>
        </box>
      </reactive-container>
    </div><!-- end row -->
    <div class="row">
      <reactive-container>
        <box box-title="近期流量">
          <div slot="box-header-ext" class="w-box-header-ext w-latest-switcher">
            <button-group :group-buttons="['新增','访问']" group-size="xs"></button-group>
          </div>
          <bar-chart :x-axis-label-rotation="-45"
                     :chart-adapter="latestAdapter" 
                     :chart-height="230"></bar-chart>
        </box>
      </reactive-container>
    </div><!-- end row -->
    <div class="row">
      <reactive-container>
        <box box-title="产品访问数据">
          <table-view :table-adapter="productProfileAdapter"></table-view>
        </box>
      </reactive-container>
    </div><!-- end row -->
    <div class="row">
      <reactive-container>
        <box box-title="近期订购">
          <div slot="box-header-ext" class="w-box-header-ext w-latest-switcher">
            <button-group :group-buttons="['7天','30天', '90天']" group-size="xs"></button-group>
          </div>
          <bar-chart :x-axis-label-rotation="-45"
                     :chart-adapter="latestAdapter" 
                     :chart-height="230"></bar-chart>
        </box>
      </reactive-container>
    </div>
  </div>
</template>

<script type="text/babel">
  import Vue from 'vue'
  import ReactiveContainer from './widgets/ReactiveContainer'
  import Box from './widgets/Box'
  import LabelText from './widgets/LabelText'
  import IconFont from './widgets/IconFont'
  import BarChart from './widgets/charts/BarChart'
  import TableView from './widgets/TableView'
  import ButtonGroup from './widgets/ButtonGroup'
  import Breadcrumb from './widgets/Breadcrumb'
  import GrowthLabel from './widgets/GrowthLabel'

  import moment from 'moment'

  import Utils from '../app/utils'

  var ProductLink = Vue.extend({
    template: '<a class="w-link" href="#" v-link="linkPath">{{ linkText }}</a>',
    props: {
      cellData: Object
    },
    computed: {
      linkPath: function () {
        var self = this
        return {
          name: 'product',
          params: {
            productId: self.cellData.id
          }
        }
      },
      linkText: function () {
        return this.cellData.name
      }
    }
  })
  Vue.component('product-link', ProductLink)

  var LatestAdapter = function () {
    this._series = []
    this._type = 0
    for (var i = 0; i < 30; i++) {
      this._series.push({
        label: '',
        value: 0
      })
    }
  }
  LatestAdapter.prototype.seriesDatas = function () {
    return this._series
  }
  LatestAdapter.prototype.pushData = function (item, index) {
    if (index !== undefined) {
      this._series.$set(index, item)
    } else {
      this._series.splice(this._series.length - 1, 1)
      this._series.splice(0, 0, item)
    }
  }
  LatestAdapter.prototype.switchType = function (type) {
    this._type = type
    this.notifyDatasetChanged()
  }

  var ProductProfileAdapter = function () {
    var self = this
    self._headers = ['产品名称', '今日新增', '昨日新增', '今日访问',
      '昨日访问', '今日订购量', '昨日订购量', '累计用户数']
    self.sortedKeys = ['productName', 'todayNew', 'yesterdayNew', 'todayVisited',
      'yesterdayVisited', 'todayOrder', 'yesterdayOrder', 'userCount']
    self.items = []

    self.header = (column, key) => self._headers[column]
    self.item = (row, column, item, key) => {
      if (key !== 'productName') {
        return item[key]
      } else {
        return {
          name: item[key],
          id: item.id
        }
      }
    }
    self.itemType = (row, column, key) => {
      if (key === 'productName') {
        return 'product-link'
      } else {
        return false
      }
    }
  }

  export default {
    data: function () {
      return {
        latestAdapter: new LatestAdapter(),
        productProfileAdapter: new ProductProfileAdapter(),
        navItems: [],
        reportData: {
          news: ['0', '0'],
          visited: ['0', '0'],
          orders: ['0', '0'],
          users: ['0', '0']
        },
        reportRawData: {
          news: [0, 0],
          visited: [0, 0],
          orders: [0, 0],
          users: [0, 0]
        }
      }
    },
    route: {
      data: function (transition) {
        var self = this
        self.$http.get('http://127.0.0.1:28084/stat/nearest?start=2016-05-29', {}, { emulateJSON: true })
          .then(function (response) {
            var responseResult = response.data.result
            var responseList = responseResult.list

            var now = moment('2016-05-25', 'YYYY-MM-DD')
            var today = now.format('YYYY-MM-DD')
            var yesterday = now.subtract(1, 'days').format('YYYY-MM-DD')

            responseList.forEach(function (item, index) {
              var value = item.value
              if (item.date === today) {
                self.reportData.news.$set(0, Utils.formatNumber(value.newUsers))
                self.reportData.visited.$set(0, Utils.formatNumber(value.visited))
                self.reportData.users.$set(0, Utils.formatNumber(value.users))
                self.reportRawData.news.$set(0, value.newUsers)
                self.reportRawData.visited.$set(0, value.visited)
                self.reportRawData.users.$set(0, value.users)
              } else if (item.date === yesterday) {
                self.reportData.news.$set(1, Utils.formatNumber(value.newUsers))
                self.reportData.visited.$set(1, Utils.formatNumber(value.visited))
                self.reportData.users.$set(1, Utils.formatNumber(value.users))
                self.reportRawData.news.$set(1, value.newUsers)
                self.reportRawData.visited.$set(1, value.visited)
                self.reportRawData.users.$set(1, value.users)
              }
              self.latestAdapter.pushData({
                label: item.date,
                data: value,
                value: function (item) {
                  var val = 0
                  if (this._type === 0) {
                    val = item.data.newUsers
                  } else {
                    val = item.data.visited
                  }
                  return val
                }
              })
              self.latestAdapter.notifyDatasetChanged()
            })
          })
        self.$http.get('http://127.0.0.1:28084/stat/app/index', {}, { emulateJSON: true })
        .then(function (response) {
          var responseResult = response.data.result
          var productList = responseResult.list
          productList.forEach(function (item) {
            self.productProfileAdapter.items.push({
              id: item.id,
              productName: item.name,
              todayNew: item.dayStat[0].value.newUsers,
              yesterdayNew: item.dayStat[1].value.newUsers,
              todayVisited: item.dayStat[0].value.visited,
              yesterdayVisited: item.dayStat[1].value.visited,
              todayOrder: item.dayStat[0].value.orders,
              yesterdayOrder: item.dayStat[1].value.orders,
              userCount: item.value.users
            })
          })
        })
        transition.next()
      },
      activate: function (transition) {
        transition.next()
      },
      deactivate: function (transition) {
        transition.next()
      }
    },
    components: {
      ReactiveContainer,
      Box,
      LabelText,
      IconFont,
      BarChart,
      TableView,
      ButtonGroup,
      Breadcrumb,
      GrowthLabel
    },
    ready: function () {
      var self = this
      self.navItems.push({
        text: '首页',
        route: {}
      })
    },
    events: {
      'ON_BUTTON_GROUP_ITEM_CLICK': function (comp, index, buttons, event) {
        this.latestAdapter.switchType(index)
      }
    }
  }
</script>

<style lang='less'>
  .w-secondary-value {
    margin-left: 4px;
    margin-right: 4px;
    font-size: 14px;
  }
  .w-yesterday-profile {
    display: block;
  }
  .w-rais-percent {
    float: right;
    margin-right: 2px;
  }
  .w-rais-percent-icon {
    margin-left: 2px;
  }
  .w-latest-switcher {
    margin-top: 6px;
  }
</style>
